<template>
  <div>
    <!-- 导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/hello' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-button type="primary" @click="openAdd">添加角色</el-button>
      <el-table :data="rolesList" style="width: 100%" border="" stripe>
        <!-- 展开列表 -->
        <el-table-column type="expand">
          <template slot-scope="scopeRow">
            <el-row
              v-for="(e, i) in scopeRow.row.children"
              :key="e.id"
              :class="['bdbottom', i==0? 'bdtop':'','venter']"
            >
              <el-col :span="5">
                <el-tag type="primary" closable @close="headClose(scopeRow.row,e.id)">{{e.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  v-for=" (ei, ii) in e.children"
                  :key="ei.id"
                  :class="[ii==0? '':'bdtop','venter']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="headClose(scopeRow.row,ei.id)"
                    >{{ei.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="eii in ei.children"
                      :key="eii.id"
                      type="warning"
                      closable
                      @close="headClose(scopeRow.row,eii.id)"
                    >{{eii.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editRole(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleRole(scope.row.id)"
            >删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="setRole(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色的对话框 -->
    <el-dialog :title="flag == 0 ? '添加角色':'编辑角色'" :visible.sync="dialogFormVisible" width="50%">
      <el-form :model="addForm" ref="addRef" :rules="addRolseRules" status-icon>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="sendAdd" v-if="flag == 0">确定添加</el-button>
        <el-button type="primary" @click="sendEdit" v-if="flag == 1">确定修改</el-button>
      </div>
    </el-dialog>
    <!-- 分配权限的对话框 -->
    <el-dialog title="分配权限" :visible.sync="powerTreeVisible" width="50%">
      <!-- 树形控件 -->
      <el-tree
        :data="TreeData"
        show-checkbox
        node-key="id"
        ref="treeRef"
        :default-expand-all="true"
        :default-checked-keys="checkedProps"
        :props="powerTreeProp"
      ></el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="powerTreeVisible = false">取 消</el-button>
        <el-button type="primary" @click="sendPower">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      flag: 0, // 0表示添加 1表示编辑
      formLabelWidth: '100px',
      rolesList: [],
      rolesId: '', // 存储当前点击的角色id
      // 添加/编辑角色对话框
      dialogFormVisible: false,
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      addRolseRules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }, { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }],
        roleDesc: [{ required: true, message: '请输入角色描述', trigger: 'blur' }, { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }]
      },
      // 权限树对话框
      powerTreeVisible: false,
      TreeData: [], // 树的数据
      checkedProps: [], // 已经勾选的数组
      powerTreeProp: {
        children: 'children',
        label: 'authName'
      }
    }
  },
  methods: {
    // 获取角色权限列表
    async getRolesList() {
      // let { data: res } = await this.$http.get('roles')
      let { data: res } = await this.$Http.getRoles()
      this.rolesList = res.data
      console.log(this.rolesList)
    },
    // 点击三级权限删除
    headClose(role, rightId) {
      this.$confirm(`此操作将永久删除该权限, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let { data: res } = await this.$Http.deleteRighes3(role.id, rightId)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          role.children = res.data
        })
        .catch(() => {
          this.$message.info('已取消删除角色权限!')
        })
    },
    // 设置角色权限
    async setRole(val) {
      // 保存当前点击的角色id
      this.rolesId = val.id
      // 放勾选的id的数组
      let arr = []
      this.powerTreeVisible = true
      // 发起请求
      let { data: res } = await this.$Http.getpowerTree(`tree`)
      // console.log(res)
      if (res.meta.status != 200) return this.$message.error(res.meta.msg)
      // 数组赋值
      this.TreeData = res.data
      this.checkedProps = this.getCheckedProps(val, arr)
      this.$message.success(res.meta.msg)
    },
    // 递归查询所有children的id
    getCheckedProps(node, arr) {
      if (!node.children) {
        arr.push(node.id)
      } else {
        node.children.forEach(e => {
          this.getCheckedProps(e, arr)
        })
      }
      return arr
    },
    // 分配权限请求
    async sendPower() {
      this.powerTreeVisible = false
      let keys = [...this.$refs.treeRef.getHalfCheckedKeys(), ...this.$refs.treeRef.getCheckedKeys()]
      let keysStr = keys.join(',')
      // 发起请求
      let { data: res } = await this.$Http.setRolesPower(this.rolesId, keysStr)
      if (res.meta.status != 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRolesList()
    },
    // 打开添加窗口
    openAdd() {
      this.dialogFormVisible = true
      this.flag = 0
      if (this.$refs.addRef) {
        this.$refs.addRef.resetFields()
      }
    },
    // 打开编辑窗口
    editRole(val) {
      this.flag = 1
      this.dialogFormVisible = true
      // console.log(val)
      this.addForm.roleName = val.roleName
      this.addForm.roleDesc = val.roleDesc
      this.rolesId = val.id
    },
    // 发送编辑请求
    sendEdit() {
      this.dialogFormVisible = false
      this.$refs.addRef.validate(async valid => {
        if (!valid) return
        let { data: res } = await this.$http.put(`roles/${this.rolesId}`, this.addForm)
        // console.log(res)
        if (res.meta.status != 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getRolesList()
      })
    },
    // 发送添加请求
    sendAdd() {
      this.dialogFormVisible = false
      this.$refs.addRef.validate(async valid => {
        if (!valid) return
        let { data: res } = await this.$http.post('roles', this.addForm)
        if (res.meta.status != 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getRolesList()
      })
    },
    // 删除角色
    deleRole(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let { data: res } = await this.$http.delete(`roles/${id}`)
          if (res.meta.status != 200) return this.$message.error(res.meta.mag)
          this.getRolesList()

          this.$message.success(res.meta.msg)
        })
        .catch(() => {
          this.$message.info('已取消删除！')
        })
    }
  },
  created() {
    this.getRolesList()
  }
}
</script>
<style lang='less' scoped>
.bdbottom {
  border-bottom: 1px solid #ccc;
}
.bdtop {
  border-top: 1px solid #ccc;
}
.el-tag {
  margin: 5px;
}
.venter {
  display: flex;
  align-items: center;
}
</style>
